<template>
  <div ref="customOptionWrapper" class="vxe-custom--option-wrapper" :class="{ 'is--active': active }">
    <ul class="vxe-custom--header">
      <li
        class="vxe-custom--option flex justify-between items-center"
        :class="[hasHeaderCustomClass]"
        :title="translateTitle('Ve.elements.全选取消')"
      >
        <div class="flex items-center">
          <!-- <span class="vxe-checkbox--icon vxe-checkbox--checked-icon" @click="selectAll"></span>
          <span class="vxe-checkbox--icon vxe-checkbox--unchecked-icon" @click="selectAll"></span>
          <span class="vxe-checkbox--icon vxe-checkbox--indeterminate-icon" @click="selectAll"></span> -->
          <el-checkbox v-model="isCheckAll" :indeterminate="isIndeterminate" :style="{ height: '15px' }" @change="selectAll" />
          <span class="vxe-checkbox--label">{{ translateTitle('Ve.elements.全部') }}</span>
        </div>
        <div>
          <button class="close-table-btn flex items-center" size="mini" @click="closeBtn">
            <vui-icon icon="close-line" />
          </button>
        </div>
      </li>
    </ul>

    <ul class="vxe-custom--body" :class="[heightSize]">
      <draggable
        class="relative"
        v-bind="eventDragOptions"
        :component-data="{
          tag: 'div',
          type: 'transition-group',
          name: 'flip-list',
        }"
        item-key="index"
        :list="getColumns"
        @end="draggableEnd"
      >
        <template #item="{ element }">
          <li class="vxe-custom--option relative level--1 flex items-center" :class="{ 'is--checked': element.visible }" :title="element.title">
            <div class="item-drag custom-item-drag">
              <vui-icon icon="drag-move-2-line" />
            </div>

            <!-- <span class="vxe-checkbox--icon vxe-checkbox--checked-icon" @click="changChecked(false, element)"></span>
            <span class="vxe-checkbox--icon vxe-checkbox--unchecked-icon" @click="changChecked(true, element)"></span> -->
            <el-checkbox v-model="element.visible" :style="{ height: '15px' }" @change="(value) => changChecked(value, element)" />
            <span class="vxe-checkbox--label">{{ element.title }}</span>
          </li>
        </template>
      </draggable>
    </ul>

    <div class="vxe-custom--footer flex justify-center">
      <button class="save-table-btn save-db-data" size="mini" @click="saveCustom">{{ btnName }}</button>
      <!-- <button class="save-table-btn" size="mini" @click="resetBtn">
        <span>重置</span>
      </button> -->
    </div>
  </div>
</template>
<script>
  import { translateTitle } from '@/utils/i18n'
  import { computed, defineComponent, onMounted, ref, watch } from 'vue'
  import { useStore } from 'vuex'
  import { useRoute } from 'vue-router'
  // import isEmpty from 'lodash/isEmpty'
  import cloneDeep from 'lodash/cloneDeep'
  import draggable from 'vuedraggable'
  import request from '@/utils/request'
  import { GFCD } from '@/utils/utils'
  import { gp } from '@vui'
  import { recursiveList } from '@ve/utils/utils'

  export default defineComponent({
    name: 'CustomOption',
    components: { draggable },
    props: {
      tableId: {
        type: String,
        default: '',
      },
      active: {
        type: Boolean,
        default: false,
      },
      isSave: {
        type: Boolean,
        default: true,
      },
      columns: {
        type: Array,
        default: () => {
          return []
        },
      },
      btnName: {
        type: String,
        default: translateTitle('Ve.elements.保存'),
      },
    },
    emits: ['saveToTable'],
    setup(props, { emit }) {
      const router = useRoute()
      const isCheckAll = ref(false) // 是否是全选状态
      const isIndeterminate = ref(false) // 是否是半选状态
      const draggableEnd = () => {
        emit('saveToTable', {
          showCustomOption: true,
          data: getColumns.value,
        })
      }
      const getColumns = ref([])
      const eventDragOptions = computed(() => {
        return {
          animation: 200,
          group: 'customOption',
          disabled: false,
          ghostClass: 'ghost',
          handle: '.custom-item-drag',
        }
      })
      // is--checked 全选了 is--indeterminate选择部分 ''都不选
      const hasHeaderCustomClass = ref('')
      //头部多选框处理
      const headerCustomFunc = () => {
        let showLength = getColumns.value.filter((v) => {
          return v.visible === true
        }).length

        if (showLength <= 0) {
          hasHeaderCustomClass.value = ''
          isCheckAll.value = false
          isIndeterminate.value = false
        }
        if (showLength > 0 && showLength < getColumns.value.length) {
          hasHeaderCustomClass.value = 'is--indeterminate'
          isCheckAll.value = false
          isIndeterminate.value = true
        }

        if (showLength >= getColumns.value.length) {
          hasHeaderCustomClass.value = 'is--checked'
          isCheckAll.value = true
          isIndeterminate.value = false
        }
      }
      const getPropsColumns = () => {
        //初始化 如果旧表格没有visible 默认为true
        getColumns.value = cloneDeep(props.columns).map((v) => {
          if (v.visible == undefined) {
            v.visible = true
          }
          return v
        })
        headerCustomFunc()
      }
      onMounted(() => {
        getPropsColumns()
      })

      watch(
        () => props.columns,
        () => {
          getPropsColumns()
        },
        { deep: true }
      )

      //单条数据选择
      const changChecked = (status, item) => {
        item.visible = status
        console.log('changChecked', { status, item })
        headerCustomFunc()
        draggableEnd()
      }
      //全选
      const selectAll = () => {
        let showLength = getColumns.value.filter((v) => {
          return v.visible === true
        }).length
        let visible = false
        if (showLength == getColumns.value.length) {
          visible = false
        } else {
          visible = true
        }
        getColumns.value = getColumns.value.map((v) => {
          v.visible = visible
          return v
        })
        headerCustomFunc()
      }
      //保存到表格-临时
      const saveToTable = () => {
        emit('saveToTable', {
          showCustomOption: false,
          data: getColumns.value,
        })
      }

      const store = useStore()
      const appCode = computed(() => store.getters['user/appCode'])
      // const getNowPageData = computed(() => store.getters['preview/getNowPageData'])

      const setPagesMods = (pageData) => {
        let obj = {}
        let _getNowPageData = recursiveList([pageData])
        let _arr = []
        _getNowPageData.forEach((v) => {
          _arr = [..._arr, ...v.pageModules]
          obj[v._id] = v
        })
        const flatData = (data, parentId = undefined) => {
          return data.reduce((prev, curr) => {
            if (parentId != undefined) {
              Object.assign(curr, {
                parentId: parentId,
              })
            }
            prev.push(curr)
            if (curr.list && curr.list.length > 0) {
              prev.push(...flatData(curr.list, curr._id))
            }
            return prev
          }, [])
        }

        let flated = flatData(_arr)

        flated.forEach((v) => {
          obj[v._id] = v
        })
        return obj
      }

      //保存到数据库-个性化方案
      const saveCustom = () => {
        emit('saveToTable', {
          showCustomOption: false,
          data: getColumns.value,
        })

        if (props.isSave) {
          let _notify = gp.$baseNotify('个性化方案保存中...', '', 'success', 'top-right', 0, false)

          const getNowPageCacheData = computed(() => store.getters['preview/getNowPageCacheData'])
          let _getNowPageMods = setPagesMods(getNowPageCacheData.value)
          if (_getNowPageMods[props.tableId]) {
            let _table = _getNowPageMods[props.tableId]
            _table.extension.tableColumns.value = getColumns.value
          }
          let _fileConfig = GFCD('dams')
          request({
            url: `${_fileConfig.domain}${_fileConfig.baseUrl}`,
            method: 'POST',
            data: {
              method: 'roleServiceImpl.standardAddUserPage',
              data: JSON.stringify({
                MENU_CODE: router.name,
                PAGE_JSON: cloneDeep(getNowPageCacheData.value),
                APP_CODE: appCode.value,
              }),
            },
          }).then((res) => {
            console.log(res)
            gp.$baseMessage('保存成功', 'success')
            _notify.close()
          })
        }
      }

      const resetBtn = () => {
        let _fileConfig = GFCD('dams')
        request({
          url: `${_fileConfig.domain}${_fileConfig.baseUrl}`,
          method: 'POST',
          data: {
            method: 'roleServiceImpl.standardEductionUserPage',
            data: JSON.stringify({
              MENU_CODE: router.name,
              APP_CODE: appCode.value,
            }),
          },
        }).then((res) => {
          console.log(res)
          gp.$baseMessage('恢复成功', 'success')
          setTimeout(() => {
            location.reload()
          }, 1000)
        })
      }

      const closeBtn = () => {
        emit('saveToTable', {
          showCustomOption: false,
          data: [],
        })
      }

      const customOptionWrapper = ref()
      const heightSize = ref('large')

      watch(
        () => props.active,
        () => {
          setTimeout(() => {
            let _top = customOptionWrapper.value.getBoundingClientRect().top
            if (_top > 200) {
              heightSize.value = 'mini'
            }
          }, 1)
        }
      )

      return {
        isCheckAll,
        isIndeterminate,
        heightSize,
        customOptionWrapper,
        eventDragOptions,
        selectAll,
        getColumns,
        changChecked,
        hasHeaderCustomClass,
        saveToTable,
        saveCustom,
        resetBtn,
        draggableEnd,
        closeBtn,
        translateTitle,
      }
    },
  })
</script>

<style scoped>
  .vxe-toolbar .vxe-custom--option-wrapper.is--active {
    display: block;
  }
  .vxe-toolbar .vxe-custom--option-wrapper .vxe-custom--header {
    padding: 0;
  }
  .vxe-toolbar .vxe-custom--option-wrapper .vxe-custom--header li {
    max-width: 16em;
    min-width: 12.5em;
    padding: 2px 1em 2px 26px;
  }
  .vxe-custom--header .vxe-custom--option .vxe-checkbox--icon {
    left: 5px;
    top: 8px;
  }
  .vxe-custom--header .vxe-checkbox--label {
    font-weight: 400;
    font-size: 12px;
  }
  .vxe-toolbar .vxe-custom--option-wrapper .vxe-custom--body {
    padding: 0.2em;
    max-height: 6.6em;
  }
  .vxe-toolbar .vxe-custom--option-wrapper .vxe-custom--body.large {
    max-height: 10.6em;
  }
  .vxe-toolbar .vxe-custom--option-wrapper .vxe-custom--body.mini {
    max-height: 6.6em;
  }
  .vxe-toolbar .vxe-custom--option-wrapper .vxe-custom--body li {
    padding: 6px 0 6px 23px;
    font-size: 12px;
  }
  .vxe-toolbar .vxe-custom--option-wrapper .vxe-custom--body li:hover {
    background: #eceff5;
  }
  .vxe-checkbox--label {
    color: #000000;
    min-height: 14px;
    display: inline-block;
  }
  .vxe-toolbar .vxe-custom--option > .vxe-checkbox--icon {
    top: 7px;
  }
  .close-table-btn {
    background-color: #fff;
    color: #555;
    padding: 4px 4px;
    height: auto;
    border-radius: 2px;
    font-weight: 600;
  }
  .close-table-btn i {
    font-size: 14px;
  }
  .vxe-toolbar .vxe-custom--option-wrapper .vxe-custom--footer {
    padding: 4px 0;
  }
  .vxe-toolbar .vxe-custom--option-wrapper .vxe-custom--footer button.save-table-btn {
    background-color: #fff;
    color: #3270ff;
    font-size: 10px;
    margin: 4px;
    padding: 6px 14px;
    height: auto;
    border-radius: 2px;
    border: 1px solid #3270ff;
    width: auto;
  }
  .vxe-toolbar .vxe-custom--option-wrapper .vxe-custom--footer button.save-db-data {
    background-color: #3270ff;
    color: #fff;
  }
  .custom-item-drag {
    top: 4px;
    left: 2px;
    color: #dedede;
    background-color: transparent;
  }
  .custom-item-drag:hover {
    color: #dbdbdb;
  }
  .vxe-custom--option .vxe-checkbox--icon {
    left: 22px;
    top: 8px;
    font-size: 14px;
  }
</style>
